﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace BasicComponents.pub
{
    /// <summary>
    /// UC_TreeComboBox.xaml 的交互逻辑
    /// </summary>
    public partial class UC_TreeComboBox : UserControl, INotifyPropertyChanged
    {
        Boolean canSelectAllLevel = true; //是否允许选择所有级次，默认是，否则只能选择末级
        String txtValue = "";
        String dm = "";
        String mc = "";
        Boolean showButtonMouseOn = true;
        Boolean showButtonAlways = false;
        public UC_TreeComboBox()
        {
            InitializeComponent();
            this.tbox_val.DataContext = this;//此处方可实现内外的绑定，若不添加只能则无法绑定
            this.tblock_dm.DataContext = this;//此处方可实现内外的绑定，若不添加只能则无法绑定
        }
        TreeViewItem selectedTVI = null;
        ObservableCollection<TreeViewItem> list_items = new ObservableCollection<TreeViewItem>();

        //设置下拉框内容
        public ObservableCollection<TreeViewItem> List_items
        {
            get => list_items;
            set
            {
                list_items = value;
                this.treeView.Items.Clear();
                //复制元素
                foreach (TreeViewItem tvi in this.List_items)
                {
                    TreeViewItem tvi_tmp = new TreeViewItem();
                    tvi_tmp.Header = tvi.Header;
                    tvi_tmp.Tag = tvi.Tag;
                    tvi_tmp.IsExpanded = tvi.IsExpanded;
                    tvi_tmp.PreviewMouseLeftButtonUp += Tvi_tmp_MouseLeftButtonDown;
                    tvi_tmp.MouseDoubleClick += Tvi_tmp_MouseDoubleClick;
                    //添加选中菜单
                    ContextMenu contextMenu = new ContextMenu();
                    MenuItem menuItem = new MenuItem();
                    menuItem.Header = "选择当前项";
                    menuItem.Tag = tvi_tmp;
                    menuItem.Click += MenuItem_Click;
                    MenuItem menuItem_openAll = new MenuItem();
                    menuItem_openAll.Header = "展开所有下级";
                    menuItem_openAll.Tag = tvi_tmp;
                    menuItem_openAll.Click += MenuItem_openAll_Click;
                    MenuItem menuItem_closeAll = new MenuItem();
                    menuItem_closeAll.Header = "折叠所有下级";
                    menuItem_closeAll.Tag = tvi_tmp;
                    menuItem_closeAll.Click += MenuItem_closeAll_Click; ;
                    contextMenu.Items.Add(menuItem);
                    contextMenu.Items.Add(menuItem_closeAll);
                    contextMenu.Items.Add(menuItem_openAll);
                    tvi_tmp.ContextMenu = contextMenu;
                    addItems(tvi, tvi_tmp);
                    tvi_tmp.KeyDown += TreeViewItem_KeyDown;
                    this.treeView.Items.Add(tvi_tmp);
                }
               // MessageBox.Show(this.treeView.Items.Count+",wxt最终下拉框内容");
                //下拉列表变化，同时更新显示内容
                getDMMCByVal(this.DM);
                OnPropertyChanged("List_items");

            }
        }
        //tree节点鼠标左键按下后弹起事件
        private void Tvi_tmp_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem tv = sender as TreeViewItem;
            if (tv is TreeViewItem)
            {
                if (!tv.HasItems)
                {
                    try
                    {
                        tv.IsSelected = true;
                        RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                        RaiseEvent(args);
                    }
                    catch (Exception e1)
                    {
                        MessageBox.Show("左键按下选择出错：" + e1.Message);
                    }
                    this.TxtValue = tv.Header.ToString();
                    this.DM = tv.Tag.ToString();
                    this.MC = tv.Header.ToString().Replace(this.DM + "-", "");
                    popup.IsOpen = false;
                    this.tbox_val.Focus();
                    Keyboard.Focus(this.tbox_val);
                }
            }
            else
            {
                e.Handled = true;
            }
        }
        //tree节点鼠标左键双击事件
        private void Tvi_tmp_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TreeViewItem tv = sender as TreeViewItem;
            if (tv is TreeViewItem)
            {
                if (!tv.HasItems)
                {
                    this.TxtValue = tv.Header.ToString();
                    this.DM = tv.Tag.ToString();
                    this.MC = tv.Header.ToString().Replace(this.DM + "-", "");
                    popup.IsOpen = false;
                    this.tbox_val.Focus();
                    Keyboard.Focus(this.tbox_val);
                }
            }
            else
            {
                e.Handled = true;
            }
        }


        //循环添加节点内容
        private void addItems(TreeViewItem tviItems, TreeViewItem tviItems_new)
        {
            foreach (TreeViewItem tvi in tviItems.Items)
            {
                TreeViewItem tvi_tmp = new TreeViewItem();
                tvi_tmp.Header = tvi.Header;
                tvi_tmp.Tag = tvi.Tag;
                tvi_tmp.IsExpanded = tvi.IsExpanded;
                tvi_tmp.MouseLeftButtonDown += Tvi_tmp_MouseLeftButtonDown;
                tvi_tmp.MouseDoubleClick += Tvi_tmp_MouseDoubleClick;
                //添加选中菜单
                ContextMenu contextMenu = new ContextMenu();
                MenuItem menuItem = new MenuItem();
                menuItem.Header = "选择当前项";
                menuItem.Tag = tvi_tmp;
                menuItem.Click += MenuItem_Click;
                MenuItem menuItem_openAll = new MenuItem();
                menuItem_openAll.Header = "展开所有下级";
                menuItem_openAll.Tag = tvi_tmp;
                menuItem_openAll.Click += MenuItem_openAll_Click;
                MenuItem menuItem_closeAll = new MenuItem();
                menuItem_closeAll.Header = "折叠所有下级";
                menuItem_closeAll.Tag = tvi_tmp;
                menuItem_closeAll.Click += MenuItem_closeAll_Click; ;
                contextMenu.Items.Add(menuItem);
                contextMenu.Items.Add(menuItem_closeAll);
                contextMenu.Items.Add(menuItem_openAll);
                tvi_tmp.ContextMenu = contextMenu;

                tvi_tmp.KeyDown += TreeViewItem_KeyDown;
                tviItems_new.Items.Add(tvi_tmp);
                addItems(tvi, tvi_tmp);
            }
        }

        //折叠所有下级
        private void MenuItem_closeAll_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TreeViewItem tvi = ((sender as MenuItem).Tag as TreeViewItem);
                loopOpenChildrens(tvi, false);
            }
            catch (Exception e1)
            {
                MessageBox.Show("折叠所有下级失败，" + e1.Message);
                throw e1;
            }
        }

        //弹出菜单选中操作
        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TreeViewItem tvi = ((sender as MenuItem).Tag as TreeViewItem);
                if (CanSelectAllLevel)
                {
                    this.TxtValue = tvi.Header.ToString();
                    this.DM = tvi.Tag.ToString();
                    this.MC = tvi.Header.ToString().Replace(this.DM + "-", "");
                    popup.IsOpen = false;
                    this.tbox_val.Focus();
                    Keyboard.Focus(this.tbox_val);
                }
                else if (!tvi.HasItems)
                {
                    this.TxtValue = tvi.Header.ToString();
                    this.DM = tvi.Tag.ToString();
                    this.MC = tvi.Header.ToString().Replace(this.DM + "-", "");
                    popup.IsOpen = false;
                    this.tbox_val.Focus();
                    Keyboard.Focus(this.tbox_val);
                }
                else if (!CanSelectAllLevel)
                {
                    MessageBox.Show("不允许选择非明细项，请选择明细项！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("弹出菜单选中操作失败，" + e1.Message);
                throw e1; 
            }
        }

        //展开所有下级
        private void MenuItem_openAll_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TreeViewItem tvi = ((sender as MenuItem).Tag as TreeViewItem);
                loopOpenChildrens(tvi, true);
            }
            catch (Exception e1)
            {
                MessageBox.Show("展开所有下级失败，" + e1.Message);
                throw e1; 
            }
        }
        //循环展开所有下级
        private void loopOpenChildrens(TreeViewItem tvi, Boolean isExpanded)
        {
            tvi.IsExpanded = isExpanded;
            foreach (TreeViewItem tv in tvi.Items)
            {
                loopOpenChildrens(tv, isExpanded);
            }
        }

        //2、内容块内容信息
        public String TxtValue
        {
            get
            {
                return this.txtValue;
            }
            set
            {
                //txtValue = value;
                this.tbox_val.Text = value;
                this.txtValue = value;
                OnPropertyChanged("TxtValue");
            }

        }
        public static readonly DependencyProperty TxtValueProperty = DependencyProperty.Register("TxtValue", typeof(String), typeof(UC_TreeComboBox), new PropertyMetadata("", (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.TxtValue = e.NewValue.ToString();
        }));

        //下拉框内容信息 wxt 20190822
        public ObservableCollection<TreeViewItem> ListTreeItems
        {
            get
            {
                return List_items;
            }
            set
            {
                //MessageBox.Show("wxt传入数据行总数："+(value as ObservableCollection<TreeViewItem>).Count);
                List_items = value; 
               // MessageBox.Show("wxt并入总数：" + (List_items as ObservableCollection<TreeViewItem>).Count);
                OnPropertyChanged("ListTreeItems");
            }

        }
        public static readonly DependencyProperty ListTreeItemsProperty = DependencyProperty.Register("ListTreeItems", typeof(ObservableCollection<TreeViewItem>), typeof(UC_TreeComboBox), new PropertyMetadata(new ObservableCollection<TreeViewItem>(), (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.ListTreeItems = e.NewValue as ObservableCollection<TreeViewItem>;
        }));

        //2、代码内容信息
        public String DM
        {
            get
            {
                return this.tblock_dm.Text;
            }
            set
            {
                this.tblock_dm.Text = value;
                getDMMCByVal(value);
                OnPropertyChanged("DM");
            }

        }
        public static readonly DependencyProperty DMProperty = DependencyProperty.Register("DM", typeof(String), typeof(UC_TreeComboBox), new PropertyMetadata("", (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.DM = e.NewValue.ToString();
        }));
        //3、PopupStaysOpen属性
        public Boolean PopupStaysOpen
        {
            get
            {
                return this.popup.StaysOpen;
            }
            set
            {
                this.popup.StaysOpen = value;
                OnPropertyChanged("PopupStaysOpen");
            }

        }
        public static readonly DependencyProperty PopupStaysOpenProperty = DependencyProperty.Register("PopupStaysOpen", typeof(Boolean), typeof(UC_TreeComboBox), new PropertyMetadata(false, (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.popup.StaysOpen = (Boolean)e.NewValue;
        }));
        //3、mouseonShowButton属性
        public Boolean ShowButtonMouseOn
        {
            get
            {
                return this.showButtonMouseOn;
            }
            set
            {
                this.showButtonMouseOn = value;
                OnPropertyChanged("ShowButtonMouseOn");
            }
        }

        public static readonly DependencyProperty ShowButtonMouseOnProperty = DependencyProperty.Register("ShowButtonMouseOn", typeof(Boolean), typeof(UC_TreeComboBox), new PropertyMetadata(true, (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.ShowButtonMouseOn = (Boolean)e.NewValue;
        }));
        //3、ShowButtonAlways属性
        public Boolean ShowButtonAlways
        {
            get
            {
                return this.showButtonAlways;
            }
            set
            {
                this.showButtonAlways = value;
                this.btn_open.Visibility = value ? Visibility.Visible : Visibility.Collapsed;
                OnPropertyChanged("ShowButtonAlways");
            }
        }

        public static readonly DependencyProperty ShowButtonAlwaysProperty = DependencyProperty.Register("ShowButtonAlways", typeof(Boolean), typeof(UC_TreeComboBox), new PropertyMetadata(true, (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.ShowButtonAlways = (Boolean)e.NewValue;
        }));
        //2、代码内容信息
        public String MC
        {
            get
            {
                return this.mc;
            }
            set
            {
                //txtValue = value;
                this.mc = value;
                OnPropertyChanged("MC");
            }

        }
        public static readonly DependencyProperty MCProperty = DependencyProperty.Register("MC", typeof(String), typeof(UC_TreeComboBox), new PropertyMetadata("", (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.MC = e.NewValue.ToString();
        }));

        //内容变化的时候，直接查找内容
        private void getDMMCByVal(String dm)
        {
            try
            {
                if (this.tbox_val.IsFocused) return;
                String keyword = dm;
                this.selectedTVI = null;
                List<TreeViewItem> list_selected = new List<TreeViewItem>();
                foreach (TreeViewItem tv in this.treeView.Items)
                {
                    getTreeViewItemsByDM(tv, keyword, ref list_selected);
                }
                //根据筛选出来的结果
                if (list_selected.Count == 1)
                {
                    this.tbox_val.Text = list_selected[0].Header.ToString();
                    //this.DM = list_selected[0].Tag.ToString();
                    this.MC = list_selected[0].Header.ToString().Replace(this.DM + "-", "");
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("按指定内容查找内容发生错误:"+e1.Message);
                throw e1 ;
            }
        }

        //3、边框的是否显示
        public new Thickness BorderThickness
        {
            get
            {
                return this.border_txt.BorderThickness;
            }
            set
            {
                this.border_txt.BorderThickness = value;
            }
        }
        public new static readonly DependencyProperty BorderThicknessProperty = DependencyProperty.Register("BorderThickness", typeof(Thickness), typeof(UC_TreeComboBox), new PropertyMetadata(new Thickness(1), (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.border_txt.BorderThickness = (Thickness)e.NewValue;
        }));
        //4、只读属性
        public Boolean IsReadOnly
        {
            get
            {
                return this.tbox_val.IsReadOnly;
            }
            set
            {
                //txtValue = value;
                this.tbox_val.IsReadOnly = value;
                this.btn_open.IsEnabled = !value;
                if (!value && (this.tbox_val.IsFocused || this.tbox_val.IsKeyboardFocused))
                {
                    this.btn_open.Visibility = Visibility.Visible;
                }
                else
                {
                    this.btn_open.Visibility = Visibility.Collapsed;
                }
                OnPropertyChanged("IsReadOnly");
            }
        }
        public static readonly DependencyProperty IsReadOnlyProperty = DependencyProperty.Register("IsReadOnly", typeof(Boolean), typeof(UC_TreeComboBox), new PropertyMetadata(false, (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.tbox_val.IsReadOnly = (Boolean)e.NewValue;
        }));
        //5、只允许选择末级明细属性
        public Boolean CanSelectAllLevel
        {
            get
            {
                return this.canSelectAllLevel;
            }
            set
            {
                //txtValue = value;
                this.canSelectAllLevel = value;
                OnPropertyChanged("CanSelectAllLevel");
            }
        }
        public static readonly DependencyProperty CanSelectAllLevelProperty = DependencyProperty.Register("CanSelectAllLevel", typeof(Boolean), typeof(UC_TreeComboBox), new PropertyMetadata(true, (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.CanSelectAllLevel = (Boolean)e.NewValue;
        }));

        //2、下拉框内容信息
        public ObservableCollection<TreeViewItem> TreeViewItems
        {
            get { return (ObservableCollection<TreeViewItem>)GetValue(TreeViewItemsProperty); }
            set { SetValue(TreeViewItemsProperty, value); }
        }
        public static readonly DependencyProperty TreeViewItemsProperty = DependencyProperty.Register("TreeViewItems", typeof(ObservableCollection<TreeViewItem>), typeof(UC_TreeComboBox), new PropertyMetadata(new ObservableCollection<TreeViewItem>(), (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.List_items = e.NewValue as ObservableCollection<TreeViewItem>;
            //resetComponentSize(sender);
        }));

        //20190716下拉框内容信息
        public TreeViewItem SelectedItem
        {
            get { return this.treeView.SelectedItem as TreeViewItem; }
            set { SetValue(SelectedItemProperty, value); }
        }
        public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(TreeViewItem), typeof(UC_TreeComboBox), new PropertyMetadata(null, (s, e) =>
        {
            UC_TreeComboBox sender = s as UC_TreeComboBox;
            sender.treeView.SetCurrentValue(TreeView.SelectedItemProperty, e.NewValue as TreeViewItem);
            //resetComponentSize(sender);
        }));

        // public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register("SelectedItem", typeof(TreeViewItem), typeof(UC_TreeComboBox));


        private void tbox_val_GotFocus(object sender, RoutedEventArgs e)
        {
            if (!this.tbox_val.IsReadOnly)
            {
                this.btn_open.Visibility = Visibility.Visible;
                this.border_txt.BorderBrush = Brushes.Black;
            }
            //MessageBox.Show(this.tbox_val.BorderBrush.ToString()+":"+Brushes.Red);
        }

        private void tbox_val_LostFocus(object sender, RoutedEventArgs e)
        {
            //  btn_open.Visibility = Visibility.Collapsed;
        }

        private void btn_open_Click(object sender, RoutedEventArgs e)
        {
            if (!this.tbox_val.IsReadOnly)
            {
                popup.IsOpen = true;
            }
            //MessageBox.Show("1111");
        }

        //20190716选择变化事件
        public event RoutedEventHandler SelectedItemChanged
        {
            add { this.AddHandler(SelectedItemChangedEvent, value); }
            remove { this.RemoveHandler(SelectedItemChangedEvent, value); }
        }
        public static readonly RoutedEvent SelectedItemChangedEvent = EventManager.RegisterRoutedEvent("SelectedItemChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UC_TreeComboBox));

        //内容变化事件
        private void tbox_val_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                this.txtValue = (sender as TextBox).Text;  //20190529注释掉，已经使用了绑定，故此处会出发两次内容变化事件
                                                           //20190529 wxt触发内容变化事件
                try
                {
                    RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.TxtValueChangedEvent, this);
                    RaiseEvent(args);
                }
                catch (Exception e1)
                {
                }
            }
            catch (Exception e1) {
                MessageBox.Show("内容变化异常，错误信息：" + e1.Message) ;
            }

        }

        //回车响应事件 ，实现筛选
        private void tbox_val_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (this.tbox_val.IsReadOnly)
                {
                    //此处是内容只读状态，请响应回车事件
                }
                else
                if (e.Key.Equals(Key.Return))
                {
                    String keyword = (sender as TextBox).Text;
                    if (keyword == null || keyword.Length <= 0)
                    {
                        popup.IsOpen = true;
                        treeView.Focus();
                        return;
                    }
                    this.selectedTVI = null;
                    List<TreeViewItem> list_selected = new List<TreeViewItem>();
                    foreach (TreeViewItem tv in this.treeView.Items)
                    {
                        getTreeViewItems(tv, keyword, ref list_selected);
                    }

                    //根据筛选出来的结果
                    if (list_selected.Count == 1)
                    {
                        if (CanSelectAllLevel)
                        {
                            this.TxtValue = list_selected[0].Header.ToString();
                            this.DM = list_selected[0].Tag.ToString();
                            popup.IsOpen = false;
                            //触发选择变化事件20190716
                            try
                            {

                                list_selected[0].IsSelected = true;
                                RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                                RaiseEvent(args);
                            }
                            catch (Exception e1)
                            {
                                MessageBox.Show("选择出错：" + e1.Message);
                            }
                            return;
                        }
                        else if (!list_selected[0].HasItems)
                        {
                            this.TxtValue = list_selected[0].Header.ToString();
                            this.DM = list_selected[0].Tag.ToString();
                            popup.IsOpen = false;
                            //触发选择变化事件20190716
                            try
                            {
                                list_selected[0].IsSelected = true;
                                RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                                RaiseEvent(args);
                            }
                            catch (Exception e1)
                            {
                                MessageBox.Show("选择出错：" + e1.Message);
                            }
                            e.Handled = true;
                            return;
                        }
                        else
                        {
                            foreach (TreeViewItem tv in list_selected)
                            {
                                tv.IsExpanded = true;
                            }
                        }
                    }
                    else
                    {
                        foreach (TreeViewItem tv in list_selected)
                        {
                            //无明细，并且直接代码则直接选择
                            if (keyword.Equals(tv.Tag.ToString()))
                            {
                                if (!tv.HasItems)
                                {
                                    this.tbox_val.Text = tv.Header.ToString();
                                    this.DM = tv.Tag.ToString();
                                    popup.IsOpen = false;
                                    //触发选择变化事件20190716
                                    try
                                    {
                                        tv.IsSelected = true;
                                        RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                                        RaiseEvent(args);
                                    }
                                    catch (Exception e1)
                                    {
                                        MessageBox.Show("选择出错：" + e1.Message);
                                    }
                                    e.Handled = true;
                                    return;
                                }
                                else if (CanSelectAllLevel)
                                {
                                    this.tbox_val.Text = tv.Header.ToString();
                                    this.DM = tv.Tag.ToString();
                                    popup.IsOpen = false;
                                    //触发选择变化事件20190716
                                    try
                                    {
                                        tv.IsSelected = true;
                                        RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                                        RaiseEvent(args);
                                    }
                                    catch (Exception e1)
                                    {
                                        MessageBox.Show("选择出错：" + e1.Message);
                                    }
                                    e.Handled = true;
                                    return;
                                }
                            }
                            tv.IsExpanded = true;
                        }
                    }
                    popup.IsOpen = true;
                    treeView.Focus();
                    e.Handled = true;
                }
            }
            catch (Exception e1)
            {
                
               MessageBox.Show("回车事件响应失败，"+e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                throw e1;
            }
        }

        //循环treeviewitems
        private void getTreeViewItems(TreeViewItem tvi, String keyword, ref List<TreeViewItem> list_selected)
        {
            if (tvi.Header.ToString().Contains(keyword))
            {
                tvi.IsExpanded = true;
                list_selected.Add(tvi);
            }
            foreach (TreeViewItem tvi_tmp in tvi.Items)
            {
                getTreeViewItems(tvi_tmp, keyword, ref list_selected);
            }
        }
        //内容变化事件
        public event RoutedEventHandler TxtValueChanged
        {
            add { this.AddHandler(TxtValueChangedEvent, value); }
            remove { this.RemoveHandler(TxtValueChangedEvent, value); }
        }
        public static readonly RoutedEvent TxtValueChangedEvent = EventManager.RegisterRoutedEvent("TxtValueChanged", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(UC_TreeComboBox));

        //循环treeviewitems 直接按照代码查找。
        private void getTreeViewItemsByDM(TreeViewItem tvi, String keyword, ref List<TreeViewItem> list_selected)
        {
            String dm = tvi.Tag.ToString();
            if (dm.Equals(keyword))
            {
                list_selected.Add(tvi);
            }
            else if (keyword.StartsWith(dm))
            {
                foreach (TreeViewItem tvi_tmp in tvi.Items)
                {
                    getTreeViewItemsByDM(tvi_tmp, keyword, ref list_selected);
                }
            }
        }

        private void treeView_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Escape))
            {
                this.popup.IsOpen = false;
                this.tbox_val.Focus();
                Keyboard.Focus(this.tbox_val);
            }
        }

        //树节点上回车事件
        private void TreeViewItem_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Return))
            {
                if (!CanSelectAllLevel)
                {
                    if (!(sender as TreeViewItem).HasItems)
                    {
                        this.TxtValue = (sender as TreeViewItem).Header.ToString();
                        this.DM = (sender as TreeViewItem).Tag.ToString();
                        this.popup.IsOpen = false;
                        this.tbox_val.Focus();
                        Keyboard.Focus(this.tbox_val);
                        e.Handled = true;
                    }
                }
                else
                {
                    this.TxtValue = (sender as TreeViewItem).Header.ToString();
                    this.DM = (sender as TreeViewItem).Tag.ToString();
                    this.popup.IsOpen = false;
                    this.tbox_val.Focus();
                    Keyboard.Focus(this.tbox_val);
                    e.Handled = true;
                    //  (sender as TreeViewItem).IsExpanded = !(sender as TreeViewItem).IsExpanded;
                }
            }
            else if (e.Key.Equals(Key.Escape))
            {
                this.popup.IsOpen = false;
                this.tbox_val.Focus();
                Keyboard.Focus(this.tbox_val);
                e.Handled = true;
            }
        }

        private void border_txt_LostFocus(object sender, RoutedEventArgs e)
        {
            if (!showButtonAlways)
            {
                this.btn_open.Visibility = Visibility.Collapsed;
            }
            this.border_txt.BorderBrush = Brushes.LightGray;
        }

        private void border_txt_GotFocus(object sender, RoutedEventArgs e)
        {
            if (!this.tbox_val.IsReadOnly)
            {
                this.btn_open.Visibility = Visibility.Visible;
            }
            this.border_txt.BorderBrush = Brushes.Black;
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string strPropertyInfo)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(strPropertyInfo));
            }
        }

        private void popup_MouseDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //e.Handled = true;
               // MessageBox.Show("popup上鼠标按下");
            }
            catch (Exception e1) {
                MessageBox.Show("popup上鼠标按下事件发生异常，"+e1.Message);
            }
        }


        private void btn_open_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (e.NewValue.Equals(Visibility.Visible))
            {
                this.border_txt.BorderBrush = Brushes.Black;
            }
            else
            {
                this.border_txt.BorderBrush = Brushes.LightGray;
            }
        }

        private void Grid_MouseEnter(object sender, MouseEventArgs e)
        {
            if (!IsReadOnly)
            {
                //if (this.tbox_val.IsKeyboardFocused)
                //{
                //    this.btn_open.Visibility = Visibility.Visible;
                //}
                //else  
                if (this.showButtonMouseOn)
                {
                    this.btn_open.Visibility = Visibility.Visible;
                }
            }
            this.border_txt.BorderBrush = Brushes.Gray;
        }

        private void Grid_MouseLeave(object sender, MouseEventArgs e)
        {
            if (!this.grid_main.IsFocused && !this.IsFocused && !this.tbox_val.IsFocused && !this.btn_open.IsFocused && !this.popup.IsFocused && !this.treeView.IsFocused)
            {
                if (!this.showButtonAlways)
                {
                    this.btn_open.Visibility = Visibility.Collapsed;
                }
                if (this.tbox_val.IsFocused)
                {
                    this.border_txt.BorderBrush = Brushes.Gray;
                }
                else
                {
                    this.border_txt.BorderBrush = Brushes.LightGray;
                }
            }
        }

        private void popup_Opened(object sender, EventArgs e)
        {
            this.border_txt.BorderBrush = Brushes.Black;
        }

        /// <summary>
        /// 组合树节点集合
        /// </summary>
        /// <returns></returns>
        public static ObservableCollection<TreeViewItem> buildTreeViewItems(String fjfa, char spliterChar, DataTable dt, String dmColName, String mcColName, Boolean isExpaned)
        {
            ObservableCollection<TreeViewItem> list = new ObservableCollection<TreeViewItem>();
            foreach (DataRow row in dt.Rows)
            {
                String dm = row[dmColName].ToString();
                String preDM = DMFJUtils.DMFJUtils.pearentDM(dm, spliterChar, fjfa);
                TreeViewItem tvi_new = new TreeViewItem();
                tvi_new.Name = "_" + row[dmColName].ToString();
                tvi_new.Header = row[dmColName] + "-" + row[mcColName];
                tvi_new.Tag = dm;
                tvi_new.IsExpanded = isExpaned;
                if (preDM == null || preDM.Trim().Equals(""))
                {
                    list.Add(tvi_new);
                }
                else
                {
                    TreeViewItem preNode = null;
                    foreach (TreeViewItem tvi_root in list)
                    {
                        preNode = getPreTreeNode(tvi_root, preDM);
                        if (preNode != null)
                        {
                            preNode.Items.Add(tvi_new);
                            break;
                        }
                    }
                    if (preNode == null)
                    {
                        list.Add(tvi_new);
                    }
                }
            }
            return list;
        }
        //遍历节点信息
        private static TreeViewItem getPreTreeNode(TreeViewItem tvi_root, String preDM)
        {
            if (tvi_root.Name.Substring(1).Equals(preDM))
            {
                return tvi_root;
            }
            else if (preDM.IndexOf(tvi_root.Name.Substring(1)) == 0 && tvi_root.HasItems)
            {
                foreach (TreeViewItem tbi in tvi_root.Items)
                {
                    TreeViewItem tvi = getPreTreeNode(tbi, preDM);
                    if (tvi != null)
                    {
                        return tvi;
                    }
                    else
                    {
                        continue;
                    }
                }
                return null;
            }
            else
            {
                return null;
            }
        }
         
        //失去焦点的时候选择内容，如果满足则选择，如果不满足则清空内容
        private void Grid_main_LostFocus(object sender, RoutedEventArgs e)
        {
            //20190716注释掉，避免误触
            if (true) { }
            else
            {
                try
                {
                    //  MessageBox.Show(this.btn_open.IsFocused.ToString() + ":" + this.popup.IsFocused.ToString());
                    if (this.tbox_val.IsReadOnly)
                    {
                        return;
                        //此处是内容只读状态，请响应回车事件
                    }
                    else
                    {
                        String keyword = this.tbox_val.Text;
                        if (keyword == null || keyword.Length <= 0)
                        {
                            return;
                        }
                        this.selectedTVI = null;
                        List<TreeViewItem> list_selected = new List<TreeViewItem>();
                        foreach (TreeViewItem tv in this.treeView.Items)
                        {
                            getTreeViewItems(tv, keyword, ref list_selected);
                        }

                        //根据筛选出来的结果
                        if (list_selected.Count == 1)
                        {
                            if (CanSelectAllLevel)
                            {
                                this.TxtValue = list_selected[0].Header.ToString();
                                this.DM = list_selected[0].Tag.ToString();
                                popup.IsOpen = false;
                                //触发选择变化事件20190716
                                try
                                {
                                    list_selected[0].IsSelected = true;
                                    RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                                    RaiseEvent(args);
                                }
                                catch (Exception e1)
                                {
                                    MessageBox.Show("选择出错：" + e1.Message);
                                }
                                return;
                            }
                            else if (!list_selected[0].HasItems)
                            {
                                this.TxtValue = list_selected[0].Header.ToString();
                                this.DM = list_selected[0].Tag.ToString();
                                popup.IsOpen = false;
                                //触发选择变化事件20190716
                                try
                                {
                                    list_selected[0].IsSelected = true;
                                    RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                                    RaiseEvent(args);
                                }
                                catch (Exception e1)
                                {
                                    MessageBox.Show("选择出错：" + e1.Message);
                                }
                                e.Handled = true;
                                return;
                            }
                            else
                            {
                                this.SelectedItem = null;
                                this.TxtValue = "";
                                this.DM = "";
                                popup.IsOpen = false;
                            }
                        }
                        else
                        {
                            foreach (TreeViewItem tv in list_selected)
                            {
                                //无明细，并且直接代码则直接选择
                                if (keyword.Equals(tv.Tag.ToString()))
                                {
                                    if (!tv.HasItems)
                                    {
                                        this.tbox_val.Text = tv.Header.ToString();
                                        this.DM = tv.Tag.ToString();
                                        popup.IsOpen = false;
                                        //触发选择变化事件20190716
                                        try
                                        {
                                            tv.IsSelected = true;
                                            RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                                            RaiseEvent(args);
                                        }
                                        catch (Exception e1)
                                        {
                                            MessageBox.Show("选择出错：" + e1.Message);
                                        }
                                        return;
                                    }
                                    else if (CanSelectAllLevel)
                                    {
                                        this.tbox_val.Text = tv.Header.ToString();
                                        this.DM = tv.Tag.ToString();
                                        popup.IsOpen = false;
                                        //触发选择变化事件20190716
                                        try
                                        {
                                            tv.IsSelected = true;
                                            RoutedEventArgs args = new RoutedEventArgs(UC_TreeComboBox.SelectedItemChangedEvent, this);
                                            RaiseEvent(args);
                                        }
                                        catch (Exception e1)
                                        {
                                            MessageBox.Show("选择出错：" + e1.Message);
                                        }
                                        return;
                                    }
                                }
                            }
                        }
                        this.SelectedItem = null;
                        this.TxtValue = "";
                        this.DM = "";
                        popup.IsOpen = false;
                    }
                }
                catch (Exception e1)
                {
                    MessageBox.Show("UC_TreeComboBox失去焦点内容检测失败，错误信息:" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }
    }
}
